package com.kuangstudy.controller.hash;

import com.kuangstudy.entity.Product;
import com.kuangstudy.vo.R;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/21 16:23
 */
@RestController
@Log4j2
public class ProductHashController {

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/hash/product/create")
    @ApiOperation("商品添加")
    public R createProduct(Product product) {
        // 1: 将产品存入到DB数据库中
        // 2: 确定HASH的key
        String key = "course:hash:" + product.getId();
        // 3 :把产品信息转换成map
        Map<String, Object> productMap = R.beanToMap(product);
        // 4: 将产品信息存入到hash中 putall等价于: 批量的 hmset key field1 value1 field2 value2 ....
        this.redisTemplate.opsForHash().putAll(key, productMap);

        // 5: 获取hash中的值
        Object title = this.redisTemplate.opsForHash().get(key, "title");
        Object price = this.redisTemplate.opsForHash().get(key, "price");
        Object description = this.redisTemplate.opsForHash().get(key, "description");
        log.info("从redis缓存中获取的值是：{},{},{}", title, price, description);

        // multiGet类似于：hmget key field1 field2 ...fieldn
        List<Map<String, Object>> list = this.redisTemplate.opsForHash().multiGet(key, Arrays.asList("title", "price", "description"));
        log.info("从redis缓存中获取的值是：{}", list);
        return R.ok();
    }

    /**
     * 商品涨价
     *
     * @param id
     * @param price
     * @return
     */
    @PostMapping("/hash/product/addprice")
    @ApiOperation("产品涨价")
    public R addprice(Integer id, Double price) {
        // 1: 将产品存入到DB数据库中
        // 2: 确定HASH的key
        String key = "course:hash:" + id;
        // 3 :把产品信息转换成map 类似于：hincrbyfloat course:hash:1 price 2.6
        this.redisTemplate.opsForHash().increment(key, "price", price);
        // 4：获取涨价的产品价格
        Object newprice = this.redisTemplate.opsForHash().get(key, "price");
        return R.ok().data("newprice", newprice);
    }

}
